package com.hansheng.action.material;

import com.hansheng.entity.MaterialEntity;
import com.hansheng.service.impl.MaterialServiceImpl;
import com.hansheng.util.JsonHelper;
import com.hansheng.util.PrintWriterHelper;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.hansheng.util.JsonHelper.OPER_FAILED;

/**
 * Created by GoldenMan on 2017/7/6.
 */
public class SaveMaterialAction extends ActionSupport implements ServletResponseAware, ServletRequestAware {
    private HttpServletResponse httpServletResponse;
    private HttpServletRequest httpServletRequest;
    private MaterialServiceImpl materialService;
    private String material;
    private String depository;
    private int fatherMid;

    public void setMaterialService(MaterialServiceImpl materialService) {
        this.materialService = materialService;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.httpServletRequest = request;
    }

    public String getMaterial() {
        return material;
    }

    public void setMaterial(String material) {
        this.material = material;
    }

    public String getDepository() {
        return depository;
    }

    public void setDepository(String depository) {
        this.depository = depository;
    }

    public int getFatherMid() {
        return fatherMid;
    }

    public void setFatherMid(int fatherMid) {
        this.fatherMid = fatherMid;
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.httpServletResponse = response;
        httpServletResponse.setContentType("text/html;charset=utf-8");
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
    }

    @Override
    public String execute() throws Exception {
        // Created by GoldenMan at 2017/7/6    TODO:判断添加的是否为一级材质
        try {
            MaterialEntity materialEntity = new MaterialEntity();
            materialEntity.setMaterial(getMaterial());
            materialEntity.setDepository(getDepository());
            if (getFatherMid() > 0)
                materialEntity.setFatherMid(getFatherMid());
            boolean flag = materialService.saveMaterial(materialEntity);
            PrintWriterHelper.send(flag ? JsonHelper.successJSONBuilder() : JsonHelper.errJSONBulider(1, OPER_FAILED));
        } catch (Exception e) {
            e.printStackTrace();
            PrintWriterHelper.send(JsonHelper.errJSONBulider(1, OPER_FAILED));
        }
        return null;
    }


}